<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="stationQueryForm" :inline="true">
        <el-form-item :label="$t('station.stationName')" prop="id">
          <el-select
            v-model="stationQueryForm.id"
            :placeholder="
              $t('common.placeholderSelect') + $t('station.stationName')
            "
            clearable
          >
            <el-option
              v-for="(item, index) in stationList"
              :key="index"
              :label="locale ? item.stationCnName : item.stationEnName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('station.stationEnable')" prop="stationEnable">
          <el-select
            v-model="stationQueryForm.stationEnable"
            :placeholder="
              $t('common.placeholderSelect') + $t('station.stationEnable')
            "
            clearable
          >
            <el-option
              v-for="(item, index) in stationEnableEnums"
              :key="index"
              :label="locale ? item.cndesc : item.endesc"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" type="primary" icon="Search">{{
            $t("common.search")
          }}</el-button>
          <el-button @click="addStation" type="primary" icon="Plus">{{
            $t("common.add")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 2. 引入通用表单对话框组件 -->
    <CommonFormDialog
      :dialog-title="dialogTitle"
      v-model="dialogVisible"
      :dialog-width="dialogWidth"
      :form-data="stationForm"
      :form-rules="stationRules"
      :submit-loading="submitLoading"
      @close="close"
      @cancel="cancel"
      @submit="handleFormSubmit"
      @before-close="handleDialogBeforeClose"
      ref="dialogRef"
    >
      <!-- 2.1 自定义表单项（插槽：标签的“名称”和“排序”） -->
      <template #formItems>
        <el-form-item :label="$t('station.stationCnName')" prop="stationCnName">
          <el-input
            v-model="stationForm.stationCnName"
            :placeholder="
              $t('common.placeholderInput') + $t('station.stationCnName')
            "
            clearable
            maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('station.stationEnName')" prop="stationEnName">
          <el-input
            v-model="stationForm.stationEnName"
            :placeholder="
              $t('common.placeholderInput') + $t('station.stationEnName')
            "
            clearable
            maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('station.stationIp')" prop="stationIp">
          <el-input
            v-model="stationForm.stationIp"
            :placeholder="
              $t('common.placeholderInput') + $t('station.stationIp')
            "
            clearable
            maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('station.stationEnable')" prop="stationEnable">
          <el-select
            v-model="stationForm.stationEnable"
            :placeholder="
              $t('common.placeholderSelect') + $t('station.stationEnable')
            "
            clearable
          >
            <el-option
              v-for="(item, index) in stationEnableEnums"
              :key="index"
              :label="locale ? item.cndesc : item.endesc"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('station.stationStatus')" prop="stationStatus">
          <el-select
            v-model="stationForm.stationStatus"
            :placeholder="
              $t('common.placeholderSelect') + $t('station.stationStatus')
            "
            clearable
          >
            <el-option
              v-for="(item, index) in stationStaEnums"
              :key="index"
              :label="locale ? item.cndesc : item.endesc"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <!-- 可扩展：如需其他表单项（如“颜色”“描述”），直接在这里添加 -->
      </template>
    </CommonFormDialog>

    <el-card>
      <el-row>
        <el-col :span="24">
          <el-card
            ><!-- 数据表格 -->
            <el-table
              max-height="600"
              :data="tableData"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                :label="$t('common.sn')"
                type="index"
                width="150"
              />

              <el-table-column
                :label="$t('station.stationCnName')"
                align="center"
                prop="stationCnName"
              />
              <el-table-column
                :label="$t('station.stationEnName')"
                align="center"
                prop="stationEnName"
              />
              <el-table-column
                :label="$t('station.stationIp')"
                align="center"
                prop="stationIp"
              />
              <el-table-column
                :label="$t('common.createTime')"
                align="center"
                prop="createTime"
              />
              <el-table-column
                :label="$t('common.updateTime')"
                align="center"
                prop="updateTime"
              />
              <el-table-column
                label="操作"
                align="center"
                width="200"
                fixed="right"
              >
                <template #default="scope">
                  <el-button
                    type="primary"
                    link
                    icon="Edit"
                    @click="updateStation(scope.row)"
                    >{{ $t('common.edit') }}</el-button
                  >
                  <el-button
                    type="danger"
                    link
                    icon="Delete"
                    @click="deleteStation(scope.row)"
                    >{{ $t('common.delete') }}</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { getstationListApi, getstationPageApi, addStationApi, updateStationApi, delStationApi } from "@/api/ems/station/station.ts";
import { getEnumListByType } from "@/api/enums";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import CommonFormDialog from "@/components/Modal/basicModal.vue"; // 引入通用组件
import { reactive, ref, onMounted, onUnmounted, watch, nextTick } from "vue";
const tableData = ref(); //表格数组
const locale = ref(window.localStorage.getItem("locale") == "zh-CN");

const dialogWidth = ref("600px");
// 1. 对话框状态
const dialogVisible = ref(false); // 对话框是否显示

const submitLoading = ref(false); // 提交按钮加载状态
const dialogRef = ref(); // 通用对话框组件引用
const { t } = useI18n();
const dialogTitle = ref(); // 对话框标题
// 2. 场站查询表单数据
const stationQueryForm = reactive({
  id: "", // 场站Id
  stationIp: "", // 场站Ip（默认1）
});
// 2. 场站新增表单数据
const stationForm = reactive({
  stationCnName: "", // 场站中文名称
  stationEnName: "", // 场站英文名称
  stationIp: "", //场站Ip
  stationEnable: null, //场站是否可用
  stationStatus: null, //场站状态
});
// 3. 标签表单校验规则
const stationRules = reactive({
  stationCnName: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("station.inputRule"), trigger: "blur" },
  ],
  stationEnName: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("station.inputRule"), trigger: "blur" },
  ],
  stationIp: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("station.inputRule"), trigger: "blur" },
  ],
});
//场站列表
const stationList = ref([]);
//场站可用列表枚举
const stationEnableEnums = ref([]);
//场站可用列表状态枚举
const stationStaEnums = ref([]);
//查询
const search = () => {
  getSelectPage();
};
const getSelectPage = () => {
  getstationPageApi(stationQueryForm).then((res) => {
    tableData.value = res.data.records;
  });
};
const getStationList = () => {
  getstationListApi().then((res) => {
    stationList.value = res.data;
  });
};
//获取场站枚举列表
const getEnumListByTypeList = async (stype) => {
  let res = await getEnumListByType({ type: stype });
  if (stype == "stationEnable") {
    stationEnableEnums.value = res.data;
  }
  if (stype == "stationStatus") {
    stationStaEnums.value = res.data;
  }
};
// 关闭对话框时，触发 update:modelValue 事件
const close = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
// 关闭对话框时，触发 update:modelValue 事件
const cancel = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//新增调出弹框
const addStation = () => {
  dialogVisible.value = true;
  Object.assign(stationForm, {
    id:null,
    stationCnName: "",
    stationEnName: "",
    stationIp: "",
    stationEnable: null,
    stationStatus: null,
  });
  dialogTitle.value = t("station.stationAdd");
};
//修改调出弹框
const stationId = ref();
const updateStation = (row) => {
  dialogTitle.value = t("station.stationUpdate");
  dialogVisible.value = true;
  stationId.value = row.id;
  Object.assign(stationForm, row);
};
const handleDialogBeforeClose = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//提交数据
const handleFormSubmit = () => {
  if (dialogTitle.value == t("station.stationAdd")) {
    addStationApi(stationForm).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  } else {
    updateStationApi(Object.assign(stationForm)).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  }
};
//删除数据
const deleteStation = (row) => {
  delStationApi(row.id).then((res) => {});
};

onMounted(() => {
  getSelectPage();
  getStationList();
  getEnumListByTypeList("stationEnable"); //获取场站可用
  getEnumListByTypeList("stationStatus"); //获取场站可用
});
onUnmounted(() => {});
</script>
<style lang="scss" scoped>
:deep(.dv-scroll-board .header) {
  background: #ddd !important;
}
:deep(.dv-scroll-board .rows .row-item) {
  background: gray !important;
}
</style>
